package com.bookmanger.server.service.impl;

import com.bookmanger.pojo.Entity.IsbnEntity;
import com.bookmanger.pojo.Entity.OverdueBorrowRecord;
import com.bookmanger.pojo.Entity.PunishmentEntity;
import com.bookmanger.pojo.VO.PunishmentVO;
import com.bookmanger.server.mapper.FineMapper;
import com.bookmanger.server.mapper.IsbnMapper;
import com.bookmanger.server.service.FineService;
import com.bookmanger.server.service.EmailService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

@Service
public class FineServiceImpl implements FineService {

    @Autowired
    private FineMapper fineMapper;
    
    @Autowired
    private IsbnMapper isbnMapper;
    
    @Autowired
    private EmailService emailService;

    @Override
    public boolean recordFine(PunishmentEntity punishmentEntity) {
        return true;
    }

    @Override
    public boolean payFine(Integer fineId) {
        return fineMapper.payFineById(fineId) > 0;
    }

    @Override
    public List<PunishmentEntity> getFinesByReaderId(Integer readerId) {
        return fineMapper.findUnpaidFinesByReaderId(readerId);
    }
    
    @Override
    public List<PunishmentEntity> getAllFinesByReaderId(Integer readerId) {
        return fineMapper.findAllFinesByReaderId(readerId);
    }
    
    @Override
    public void checkOverdueBooksAndSendNotifications() {
        // 查询需要检查的借阅记录
        List<OverdueBorrowRecord> records = fineMapper.findBorrowRecordsForOverdueCheck();
        
        LocalDateTime now = LocalDateTime.now();
        
        for (OverdueBorrowRecord record : records) {
            // 检查是否逾期
            if (record.getDueTime().isBefore(now)) {
                // 图书已逾期，创建罚款记录
                PunishmentEntity fine = new PunishmentEntity();
                fine.setManagerId(1); // 系统管理员ID，默认为1
                fine.setReaderId(record.getReaderId());
                fine.setBookId(record.getBookId());
                fine.setPunNum(new java.math.BigDecimal("10.00")); // 罚款金额10元
                fine.setPunCause("图书逾期未还");
                
                if (record.getReaderEmail() != null && !record.getReaderEmail().isEmpty()) {
                    // 发送逾期罚款通知邮件
                    String subject = "图书逾期罚款通知";
                    String content = String.format("您借阅的图书《%s》已逾期，请尽快归还并缴纳10元罚款。", record.getBookTitle());
                    emailService.sendEmail(record.getReaderEmail(), subject, content);
                }
                
                // 记录罚款
                fineMapper.insert(fine);
            } 
            // 检查是否将在24小时内到期
            else if (record.getDueTime().isBefore(now.plusHours(24))) {
                // 发送即将到期提醒邮件
                if (record.getReaderEmail() != null && !record.getReaderEmail().isEmpty()) {
                    String subject = "图书即将到期提醒";
                    String content = String.format("您借阅的图书《%s》将在24小时内到期，请及时归还。", record.getBookTitle());
                    emailService.sendEmail(record.getReaderEmail(), subject, content);
                }
            }
        }
    }
    
    @Override
    public boolean recordLossBookFine(Integer readerId, Integer isbnId, Integer managerId) {
        // 查询ISBN信息获取图书价格
        IsbnEntity isbnEntity = isbnMapper.selectById(isbnId);
        if (isbnEntity == null) {
            return false;
        }
        
        // 创建罚款记录
        PunishmentEntity fine = new PunishmentEntity();
        fine.setManagerId(managerId);
        fine.setReaderId(readerId);
        fine.setBookId(isbnId); // 在丢失图书的情况下，使用isbnId作为bookId
        fine.setPunNum(isbnEntity.getPrice()); // 使用图书价格作为罚款金额
        fine.setPunCause("丢失图书 " + isbnEntity.getIsbn()); // 罚款原因
        fine.setPunTime(LocalDateTime.now());
        
        // 记录罚款
        return fineMapper.insert(fine) > 0;
    }
    
    @Override
    public PageInfo<PunishmentEntity> getAllFines(Integer page, Integer pageSize) {
        // 使用PageHelper进行分页
        PageHelper.startPage(page, pageSize, true);
        List<PunishmentEntity> fines = fineMapper.findAllFines();
        return new PageInfo<>(fines);
    }
    
    @Override
    public PageInfo<PunishmentVO> getAllFinesWithReaderDetails(Integer page, Integer pageSize) {
        // 使用PageHelper进行分页
        PageHelper.startPage(page, pageSize, true);
        List<PunishmentVO> fines = fineMapper.findAllFinesWithReaderDetails();
        return new PageInfo<>(fines);
    }
    
    @Override
    public PageInfo<PunishmentVO> getFinesByReaderIdOrName(String keyword, Integer page, Integer pageSize) {
        // 使用PageHelper进行分页
        PageHelper.startPage(page, pageSize, true);
        List<PunishmentVO> fines = fineMapper.findFinesByReaderIdOrName(keyword);
        return new PageInfo<>(fines);
    }
}